<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>临时 Token 下载</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 600px;
      margin: 50px auto;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      background: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    h1 {
      color: #333;
      text-align: center;
    }
    .user-info {
      background-color: #e7f3ff;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 20px;
      border-left: 4px solid #007bff;
    }
    .download-section {
      text-align: center;
      margin: 30px 0;
    }
    .download-btn {
      display: inline-block;
      padding: 12px 24px;
      background-color: #28a745;
      color: white;
      text-decoration: none;
      border-radius: 4px;
      cursor: pointer;
      border: none;
      font-size: 16px;
    }
    .download-btn:hover {
      background-color: #218838;
    }
    .logout-btn {
      float: right;
      padding: 8px 16px;
      background-color: #dc3545;
      color: white;
      text-decoration: none;
      border-radius: 4px;
      border: none;
      cursor: pointer;
    }
    .logout-btn:hover {
      background-color: #c82333;
    }
    .status {
      margin-top: 20px;
      padding: 10px;
      border-radius: 4px;
      text-align: center;
    }
    .status.success {
      background-color: #d4edda;
      color: #155724;
      border: 1px solid #c3e6cb;
    }
    .status.error {
      background-color: #f8d7da;
      color: #721c24;
      border: 1px solid #f5c6cb;
    }
  </style>
</head>
<body>
  <div class="container">
    <button class="logout-btn" onclick="logout()">登出</button>
    <h1>双Token文件下载系统</h1>
    
    <div class="user-info">
      <strong>系统状态：</strong>已登录<br>
      <strong>Token状态：</strong><span id="tokenStatus">检查中...</span>
    </div>
    
    <div class="download-section">
      <h3>安全文件下载</h3>
      <p>点击下面的按钮下载测试文件。系统会自动获取临时Token并开始下载。</p>
      <button class="download-btn" onclick="handleDownload()">下载测试文件</button>
    </div>
    
    <div id="statusMessage" class="status" style="display: none;"></div>
  </div>

  <script>
    // 从本地存储中获取长期 Token
    const longLivedToken = localStorage.getItem('auth_token');

    // 如果长期 Token 不存在，跳转到登录页
    if (!longLivedToken) {
      window.location.href = '/login.html';
    }

    let tempToken = null;

    // 显示状态消息
    function showStatus(message, isError = false) {
      const statusDiv = document.getElementById('statusMessage');
      statusDiv.textContent = message;
      statusDiv.className = 'status ' + (isError ? 'error' : 'success');
      statusDiv.style.display = 'block';
      
      // 3秒后自动隐藏
      setTimeout(() => {
        statusDiv.style.display = 'none';
      }, 3000);
    }

    // 更新Token状态显示
    function updateTokenStatus(status) {
      document.getElementById('tokenStatus').textContent = status;
    }

    // 通过 AJAX 获取临时 Token
    async function fetchTempToken() {
      try {
        updateTokenStatus('获取临时Token中...');
        console.log('当前长期Token:', longLivedToken); // 添加调试日志
        
        const response = await fetch('/get-temp-token', {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${longLivedToken}`,
          },
        });
        
        console.log('响应状态:', response.status); // 添加调试日志
        const data = await response.json();
        console.log('响应数据:', data); // 添加调试日志
        
        if (response.ok) {
          tempToken = data.tempToken;
          updateTokenStatus('临时Token已获取');
          return true;
        } else {
          throw new Error(data.error || '获取临时 Token 失败');
        }
      } catch (error) {
        console.error('获取临时Token失败:', error); // 添加详细错误日志
        updateTokenStatus('Token获取失败');
        
        // 根据错误类型决定是否登出
        if (error.message.includes('401') || error.message.includes('身份认证')) {
          showStatus('身份认证失败，请重新登录', true);
          setTimeout(() => {
            logout();
          }, 2000);
        } else {
          // 网络错误或其他错误，不自动登出
          showStatus(`获取Token失败: ${error.message}`, true);
        }
        return false;
      }
    }

    // 点击下载时触发
    async function handleDownload() {
      showStatus('准备下载...');
      
      if (!tempToken) {
        const success = await fetchTempToken();
        if (!success) return;
      }

      // 构造带临时 Token 的下载链接
      const downloadUrl = `/download?tempToken=${encodeURIComponent(tempToken)}`;
      
      // 创建隐藏的a标签进行下载
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = 'example.txt';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 下载后清空临时token（因为是一次性的）
      tempToken = null;
      updateTokenStatus('临时Token已使用');
      showStatus('文件下载已开始');
    }

    // 登出功能
    function logout() {
      localStorage.removeItem('auth_token');
      showStatus('已登出');
      setTimeout(() => {
        window.location.href = '/login.html';
      }, 1000);
    }

    // 页面加载时预获取临时 Token
    fetchTempToken();
  </script>
</body>
</html>